﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using System.IO;
using System.Threading;

namespace wallstreet
{
    public partial class Control_MyStocks_Add : PhoneApplicationPage
    {
        List<StockInfo> allStockList = new List<StockInfo>();

        public Control_MyStocks_Add()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);
            
            loadAllStocks();
        }


        private void loadAllStocks()
        {
            try
            {
                //StreamResourceInfo res = Application.GetResourceStream(new Uri("wallstreet;component/Resources/StockTicker.txt", UriKind.Relative));
                StreamResourceInfo res = Application.GetResourceStream(new Uri("Resources/StockTicker.txt", UriKind.Relative));
                StreamReader st = new StreamReader(res.Stream);
                string line = "";

                while ((line = st.ReadLine()) != null)
                {
                    string[] words = line.Split(';');

                    allStockList.Add(new StockInfo
                    {
                        Symbol = words[0].ToUpper(),
                        Company = words[1],
                        StockExchange = words[2]
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btnBack_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void lboMyStocks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StockInfo selectedStock = lboMyStocks.SelectedItem as StockInfo;

            if(selectedStock != null)
            {
                List<StockInfo> stockList = new List<StockInfo>();

                if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList"))
                    stockList = IsolatedStorageSettings.ApplicationSettings["stockList"] as List<StockInfo>;

                var stock =
                    from s in stockList
                    orderby s.Company
                    where s.Symbol.ToLower() == selectedStock.Symbol.ToLower()
                    select s;

                List<StockInfo> list = stock.ToList();
                if (list.Count == 0)
                {
                    stockList.Add(selectedStock);

                    if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList"))
                        IsolatedStorageSettings.ApplicationSettings["stockList"] = stockList;
                    else
                        IsolatedStorageSettings.ApplicationSettings.Add("stockList", stockList);

                    if (IsolatedStorageSettings.ApplicationSettings.Contains("stockList_changed"))
                        IsolatedStorageSettings.ApplicationSettings["stockList_changed"] = "true";
                    else
                        IsolatedStorageSettings.ApplicationSettings.Add("stockList_changed", "true");

                    MessageBox.Show(selectedStock.Company + " was added to your stocklist");
                }
            }
        }

        private void btnSearch_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Thread startThread = new Thread(startLoadingThread);
            startThread.IsBackground = true;
            startThread.Start();

            var stock =
            from s in allStockList
            orderby s.Company
            where s.Company.ToLower().Contains(txtSearch.Text.ToLower())
            select s;

            List<StockInfo> list = stock.ToList();
            lboMyStocks.ItemsSource = list;

            Thread endThread = new Thread(endLoadingThread);
            endThread.IsBackground = true;
            endThread.Start();
        }

        private void startLoadingThread()
        {
            Dispatcher.BeginInvoke(delegate()
                {
                    lboMyStocks.Visibility = Visibility.Collapsed;
                    lblLoading.Visibility = Visibility.Visible;
                }
            );
        }

        private void endLoadingThread() 
        {
            Dispatcher.BeginInvoke(delegate()
                {
                    lboMyStocks.Visibility = Visibility.Visible;
                    lblLoading.Visibility = Visibility.Collapsed;
                }
            );
        }

    }
}